package com.fish.utils;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpsUtil {    
	private static final Log LOG = LogFactory.getLog(HttpsUtil.class);
	
	public static final String CHARACTER_ENCODING = "UTF-8";
	public static final String PATH_SIGN = "/";
	public static final String METHOD_POST = "POST";
	public static final String METHOD_GET = "GET";
	public static final String CONTENT_TYPE = "Content-Type";

	public static String requestPostForm(String url, Map<String, String> requestParas, String requestCharacter, String responseCharacter) {
		try{
			HttpClient client = null;
			if (url.startsWith("https")) {
				client =createHttpsClient();
			}else{
				client =createHttpClient();
			}
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formParams = initNameValuePair(requestParas);
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, requestCharacter));
			HttpResponse httpResponse = client.execute(httpPost); //执行POST请求
			HttpEntity entity = httpResponse.getEntity();             //获取响应实体
			if (entity!=null) {
				return EntityUtils.toString(entity, responseCharacter);
			}
		}catch(IOException e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	public static String requestPostForm(String url, Map<String, String> requestParas) {
		return requestPostForm(url, requestParas, CHARACTER_ENCODING, CHARACTER_ENCODING);
	}
	
	public static HttpClient createHttpClient() {
            return new DefaultHttpClient();
	}
	
    public static HttpClient createHttpsClient()  {
        try { 
        	HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 
            //TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext 
            SSLContext ctx = SSLContext.getInstance("TLS"); 
            //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用 
            ctx.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null); 
            //创建SSLSocketFactory 
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); 
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
            return httpClient;
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    	return null;
    }
    
    public static List<NameValuePair> initNameValuePair(Map<String, String> params) {
    	List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    	Set<String> set = params.keySet();
    	for (String key : set) {
    		LOG.info(key+" = " +params.get(key));
    		formParams.add(new BasicNameValuePair(key, params.get(key))); 
		}
    	return formParams;
    }
	
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	} 
	
	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

}
